package com.study.security.web.controller;


import com.fasterxml.jackson.annotation.JsonView;
import com.study.security.core.properties.SecurityProperties;
import com.study.security.web.dto.User;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.builder.ReflectionToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private SecurityProperties securityProperties;



    /**
     * 返回当前用户信息
     *
     * @return
     */
    @GetMapping("/me")
    public Object getCurrentUser(Authentication user, HttpServletRequest request) throws Exception {
        String header = request.getHeader("Authentication");
        String token = StringUtils.substringAfter(header, "bearer ");
        Claims claims = Jwts.parser().setSigningKey(
                securityProperties.getOauth2().getJwtSigningKey().getBytes("UTF-8"))
                .parseClaimsJws(token).getBody();
        String company = (String) claims.get("company");
        System.out.println("company"+company);
        return user;
    }

    @GetMapping("/me2")
    public Object getCurrentUser2(Authentication authentication) {
        return authentication;
    }

    @GetMapping("/me3")
    public Object getCurrentUser3(@AuthenticationPrincipal UserDetails user) {
        return user;
    }

    @DeleteMapping("/{id:\\d+}")
    public void delete(@PathVariable(value = "id") String id) {
        System.out.println(id);
    }

    @PutMapping("/{id:\\d+}")
    public User update(@Valid @RequestBody User user, BindingResult errors) {
        if (errors.hasErrors()) {
            errors.getAllErrors().stream().forEach(error -> {
                FieldError field = (FieldError) error;
                System.out.println(field.getField() + " " + error.getDefaultMessage());
                //System.out.println(error.getDefaultMessage());
            });
        }
        System.out.println(user.getId());
        System.out.println(user.getUsername());
        System.out.println(user.getPassword());
        System.out.println(user.getBirthday());
        user.setId("1");
        return user;
    }

    @PostMapping
    public User create(@Valid @RequestBody User user, BindingResult errors) {
        if (errors.hasErrors()) {
            // 为什么要加stream()方法
            // errors.getAllErrors().forEach(error ->
            // System.out.println(error.getDefaultMessage()));
            errors.getAllErrors().stream().forEach(error -> {
//				FieldError field = (FieldError) error;
//				System.out.println(field.getField() +" "+ error.getDefaultMessage());
                System.out.println(error.getDefaultMessage());
            });
        }
        System.out.println(user.getId());
        System.out.println(user.getUsername());
        System.out.println(user.getPassword());
        System.out.println(user.getBirthday());
        user.setId("1");
        return user;
    }

    /**
     * 如果在传参数的时候，有pageable对象，若参数中有其他对象字段与pageable字段重复，则会优先映射其他对象的同名字段
     *
     * @param user
     * @param pageable
     * @return
     */
    // @RequestMapping(value = "/user", method = RequestMethod.GET)
    @GetMapping
    @JsonView(User.UserSimpleView.class)
    @ApiOperation(value = "用户查询操作")
    public List<User> query(User user, Pageable pageable) {
        // 利用反射将对象打印出来
        System.out.println(ReflectionToStringBuilder.toString(user, ToStringStyle.MULTI_LINE_STYLE));
        System.out.println(pageable.getPageSize());
        System.out.println(pageable.getPageNumber());
        System.out.println(pageable.getSort());
        List<User> list = new ArrayList<User>();
        list.add(user);
        list.add(user);
        list.add(user);
        return list;
    }

    @GetMapping("/{id:\\d+}")
    @JsonView(User.UserDetailView.class)
    public User getInfo(@ApiParam(value = "用户id") @PathVariable("id") String id) {
//		throw new UserIsNotExistsException(id);
//        throw new RuntimeException();
        System.out.println("进入get info 服务");
        User user = new User();
        user.setUsername("tom");
        return user;
    }

}

